package org.mags.cryptography.common;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import org.apache.commons.codec.binary.Base64;

public class AESCryptoText implements ICryptoText {
	private static final byte[] KEY={24, 50, -25, 44, 25, 78, -5, 0, 120, 78, -1, 10, -100, 55, 33, 6};

	@Override
	public String encrypt(String text) {
    	try {
            Key key = new SecretKeySpec(KEY, "AES");
            Cipher c = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(text.getBytes());
            String encryptedText = Base64.encodeBase64String(encValue);
            if(encryptedText.endsWith("\r\n")) 
            	encryptedText = encryptedText.substring(0, encryptedText.length()-2);
            return encryptedText;
    	} catch(Exception e) {
			if(e instanceof RuntimeException)
				throw (RuntimeException)e;
			else
				throw new RuntimeException(e);
    	}
	}
	@Override
	public String decrypt(String text) {
    	try {
            Key key = new SecretKeySpec(KEY, "AES");
            Cipher c = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] enctVal = c.doFinal(Base64.decodeBase64(text));
            String decryptedText = new String(enctVal);
            return decryptedText;
    	} catch(Exception e) {
			if(e instanceof RuntimeException)
				throw (RuntimeException)e;
			else
				throw new RuntimeException(e);
    	}
	}
}
